#include "tg_document.h"
#include "tg_page.h"
#include "tg_pagesettings.h"

#include <QGraphicsDropShadowEffect>

TgDocument::TgDocument(QObject *parent) :
    BaseClass(parent),
    m_pageShadow(new QGraphicsDropShadowEffect(this)),
    m_dpi(TgDocument::defaultDpi)
{
    m_pageShadow->setXOffset(2.);
    m_pageShadow->setYOffset(2.);
}

TgDocument::~TgDocument()
{
    clear();
}

TgPageSettings* TgDocument::createPageSettings()
{
    TgPageSettings* settings = new TgPageSettings(this);
    m_pageSettings.append(settings);
    return settings;
}

TgPage* TgDocument::createPage()
{
    return createPage(currentPageSettings());
}

TgPage* TgDocument::createPage(TgPageSettings *settings)
{
    TgPage* page = new TgPage(settings);
    page->setGraphicsEffect(m_pageShadow);
    m_pages.append(page);
    addItem(page);
    return page;
}

TgPageSettings* TgDocument::currentPageSettings() const
{
    TgPageSettings* settings = 0;
    if( m_pageSettings.isEmpty() )
    {
        settings = const_cast<TgDocument*>(this)->createPageSettings();
    }
    else
    {
        settings = m_pageSettings.last();
    }
    return settings;
}

void TgDocument::setPageOrientation(QPrinter::Orientation orientation)
{
    TgPageSettings* settings = currentPageSettings();
    settings->setPageOrientation(orientation);
}

void TgDocument::setDpi(int dpi)
{
    if( dpi > TgDocument::maximumDpi )
    {
        dpi = TgDocument::maximumDpi;
    }
    else if( dpi < TgDocument::minimumDpi )
    {
        dpi = TgDocument::minimumDpi;
    }

    if(dpi != m_dpi)
    {
        //TODO: Dpi changed
        m_dpi = dpi;
        emit dpiChanged(this, m_dpi);
    }
}

void TgDocument::clear()
{
    foreach(TgPage* page, m_pages)
    {
        delete page;
    }
    m_pages.clear();

    foreach(TgPageSettings* settings, m_pageSettings)
    {
        delete settings;
    }
    m_pageSettings.clear();
}
